package com.daydayup.t20180914;

import java.io.Serializable;
import java.lang.reflect.Method;

public class BeanConvertUtil {
	private static final String GET_PREFIX = "get";
	private static final String SET_PREFIX = "set";

	public static void beanConvert(Serializable source, Serializable target) throws Exception {
		Class<? extends Serializable> sourceClass = source.getClass();
		Class<? extends Serializable> targetClass = target.getClass();
		Method[] sourceMethods = sourceClass.getMethods();
		for (Method sourceMethod : sourceMethods) {
			String methodName = sourceMethod.getName();
			if (methodName.startsWith(GET_PREFIX)) {
				try {
					Method targetMethod = targetClass.getMethod(methodName);
					Class<?> returnType = targetMethod.getReturnType();
					Object sourceObj = sourceMethod.invoke(source);
					Object targetObj = targetMethod.invoke(target);
					String setterMethodName = SET_PREFIX + methodName.substring(3);
					Method sourceSetterMethod = sourceClass.getMethod(setterMethodName, returnType);
					Method targetSetterMethod = targetClass.getMethod(setterMethodName, returnType);
					sourceSetterMethod.invoke(source, targetObj);
					targetSetterMethod.invoke(target, sourceObj);
				} catch (NoSuchMethodException e) {
					continue;
				}
			}
		}
	}
}